package com.cloud.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author kangwen
 */
@Component("authFilter")
public class AuthFilter implements GlobalFilter {
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpResponse response = exchange.getResponse();

		// token一般会放到header中，(可根据实际情况自己调整)
		String token = exchange.getRequest().getHeaders().getFirst("token");
		String token1 = exchange.getRequest().getQueryParams().getFirst("token");
		if (StringUtils.isBlank(token) && StringUtils.isBlank(token1)) {

			// 响应消息内容对象
			JSONObject message = new JSONObject();
			message.put("code", -1);
			message.put("msg", "缺少凭证");
			// 转换响应消息内容对象为字节
			byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
			DataBuffer buffer = response.bufferFactory().wrap(bits);
			// 设置响应对象状态码 401
			response.setStatusCode(HttpStatus.UNAUTHORIZED);
			// 设置响应对象内容并且指定编码，否则在浏览器中会中文乱码
			response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
			return response.writeWith(Mono.just(buffer));
		}
		return chain.filter(exchange);
	}
}
